Sessions Management in Django

Manish Patel

Sep 2, 2023

Django Session Management

  • Session management is a crucial aspect of web development.
  • Django provides robust tools and concepts to handle sessions securely.
  • stores per site visitor data on server side abstracting send/receive of cookie(cookie has session id and not the data)
  • django stores session in database (makemigrations and migrate are must)
    • file based session (set SESSION_ENGINE TO “django.contrib.sessions.backends.file”
    • cookie based session (set SESSION_ENGINE TO “django.contrib.sessions.backends.signed_cookies” with crypto and secretkey sign)
    • cached session

Key concepts of session management

  1. Session:
    • A session is a mechanism for storing data on the server that is associated with a particular user or client. It allows you to persist data across multiple requests and responses.
    • In Django, sessions are implemented using cookies or database-backed storage, depending on your configuration.
  2. Session Middleware:
    • Django uses middleware to handle sessions. The django.contrib.sessions.middleware.SessionMiddleware middleware is responsible for managing sessions.
    • This middleware processes incoming requests, retrieves session data, and sets a session cookie in the response.
  3. Session Engine:
    • Django supports multiple session engines, including database-backed, cache-backed, and file-based storage.
    • You can configure the session engine in your project’s settings using the SESSION_ENGINE setting.
  4. Session Configuration:
    • You can customize session settings in your Django project’s settings file (settings.py), including the session engine, session cookie name, and session expiration.
    • Example: SESSION_ENGINE, SESSION_COOKIE_NAME, SESSION_COOKIE_AGE, SESSION_EXPIRE_AT_BROWSER_CLOSE, etc.

  1. Session Data:
    • Session data is stored as key-value pairs and can include various types of data, such as user authentication status, user preferences, shopping cart contents, etc.
    • Data stored in sessions is typically small and used for temporary storage.
  2. CSRF Protection:
    • Django includes built-in CSRF protection for forms. It ensures that forms submitted to your site are generated by your server and not by malicious third-party sites.
    • CSRF tokens are included in forms using the {% csrf_token %} template tag.
  3. Session Security:
    • Django provides security mechanisms to protect session data, including encryption and signing of session cookies.
    • Session data is typically stored server-side, making it more secure than client-side storage (e.g., cookies).
  4. Session Expiry:
    • You can set an expiration time for sessions using the SESSION_COOKIE_AGE setting. Sessions can expire after a specific duration of inactivity.
    • You can also configure sessions to expire when the user’s browser is closed (SESSION_EXPIRE_AT_BROWSER_CLOSE).

  1. Session-Based Authentication:
    • Django’s authentication system often relies on sessions to manage user authentication. It stores user authentication data in the session after a successful login.
  2. Session Storage:
    • Django stores session data in the backend, which can be a database, cache, or file system, depending on the session engine you choose.
    • The default session engine is database-backed, which stores session data in the database.
  3. Session Cleanup:
    • Django includes a cleanup mechanism to remove expired sessions from the session store to free up resources.
    • You can configure how often this cleanup process runs using the SESSION_COOKIE_AGE setting.
  4. Session Middleware Order:
    • The order of middleware matters. Ensure that the SessionMiddleware is placed after SessionMiddleware in the MIDDLEWARE setting of your project’s settings file.

Django Session Management Demo

  • check session - settings/privacy and security/site settings/cookie data/see all cookie data
  • Remove all cookies and turn on allow sites to store session

Step 1: Create a Django Project and App

  • First, create a new Django project and a corresponding app:
django-admin startproject session_management_project
cd session_management_project
python manage.py startapp student
  • Register app in the settings

Step 2: Create Views

Create views for the URL patterns defined above in session_app/views.py:

from django.shortcuts import render, redirect

def setsession(request):
    request.session['name'] = 'manish'
    return render(request, 'student/setsession.html')

def getsession(request):
    name = request.session['name']
    return render(request, 'student/getsession.html', {'name': name})
    
def delsession(request):
    if 'name' in request.session:
        del request.session['name']
    #request.session.flush()
    return render(request, 'student/delsession.html')

Step 3: Create Templates

Create HTML templates for your views in the session_app/templates/session_app directory:

  • setsession.html:
<!DOCTYPE html>
<html>
<head>
    <title>Session Management Demo</title>
</head>
<body>
    <h1>Session is set </h1>
   
</body>
</html>

Get session html

  • get_session.html:
<!DOCTYPE html>
<html>
<head>
    <title>Session Value</title>
</head>
<body>
    <h1>Session Value is {{ name }} </h1>

</body>
</html>

Delete session html

  • delsession.html:
<!DOCTYPE html>
<html>
<head>
    <title>Clear Session</title>
</head>
<body>
    <h1>Session is cleared </h1>
  </body>
</html>

Step 4: Configure URLs

In your project’s urls.py (located in session_management_project/urls.py), include the URLs from your app:

# session_management_project/urls.py

from student import views
urlpatterns = [
    path("set/", views.setsession),
    path("get/", views.getsession),
    path("get/", views.delsession),
]

Step 5: Run Migrations

Run database migrations to create the necessary database tables for sessions:

python manage.py makemigrations
python manage.py migrate

Step 6: Run the Development Server

Start the Django development server:

python manage.py runserver
  • Your comprehensive session management demo should now be accessible at http://localhost:8000.

  • You can test the functionality by:

    • Setting session variables with the “Set Session” form.
    • Getting session variables by clicking the “Get Session Value” link.
    • Clearing the session using the “Clear Session” form.